<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="false">
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-collapse v-model="activeKey">
          <a-collapse-panel key="1" header="基本信息">
            <a-row :gutter="48">
              <a-col :span="8">
                <a-form-model-item label="单据编号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="billNo">
                  <a-input :disabled="formDisabled" v-model="model.billNo" :max-length="36" placeholder="请输入单据编号" disabled ></a-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="申请时间" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="createTime">
                  <j-date
                    placeholder="请选择申请时间"
                    v-model="model.createTime"
                    :show-time="true"
                    date-format="YYYY-MM-DD HH:mm:ss"
                    style="width: 100%"
                    disabled
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="申请人" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="employeeId">
                  <select-user-by-dep
                    :multi="false"
                    v-model="model.employeeId"
                    disabled></select-user-by-dep>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="申请部门" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="departId">
                  <j-select-depart :disabled="formDisabled" v-model="model.departId" disabled/>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="申请人所属团队" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="teamId">
                  <select-team-input
                    :disabled=formDisabled
                    v-model="model.teamId" :tdlx="3"/>
                </a-form-model-item>
              </a-col>
            </a-row>
          </a-collapse-panel>
          <a-collapse-panel key="2" header="查阅信息">
            <a-row :gutter="48">
              <a-col :span="8">
                <a-form-model-item label="档案大类" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="docBigCategory">
                  <j-dict-select-category
                    :disabled="formDisabled"
                    v-model="model.docBigCategory"
                    placeholder="请选择档案大类"
                    parentCode="A04"
                    :async="true"
                    @input="modifyCategory"/>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="档案小类" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="docSmallCategory">
                  <j-dict-select-category
                    :disabled="formDisabled || !model.docBigCategory"
                    v-model="model.docSmallCategory"
                    placeholder="请选择档案小类"
                    :parentCode="model.docBigCategory"
                    :async="true"
                    @input="modifySmallCategory"/>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="文件名称" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="docName">
                  <a-input
                    v-if="formDisabled"
                    readOnly
                    @click.prevent="goDocDetail(model)"
                    v-model="model.docBillNo"
                    style="color: #1890FF; cursor: pointer;"
                    placeholder="请选择文件名称"></a-input>
                  <SelectOaDocBaseInput
                    v-else-if="model.docBigCategory=='A04A01' || model.docBigCategory=='A04A02'"
                    :disabled="formDisabled || !model.docSmallCategory"
                    :multi="false"
                    v-model="model.docName"
                    @back="selectDoc"
                    :docBigCategory="model.docBigCategory"
                    :docSmallCategory="model.docSmallCategory" ></SelectOaDocBaseInput>
                  <SelectProjectArchiveInput
                    v-else
                    :disabled="formDisabled || !model.docSmallCategory"
                    :multi="false"
                    v-model="model.docName"
                    @back="selectProjectArchive"
                    :docBigCategory="model.docBigCategory"
                    :docSmallCategory="model.docSmallCategory" ></SelectProjectArchiveInput>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="密级" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="docClassification">
                  <j-dict-select-tag
                    type="list"
                    v-model="model.docClassification"
                    dictCode="secrecy_level"
                    placeholder="请选择密级"
                    disabled/>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="存放位置" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="docAddress">
                  <a-input :disabled="formDisabled" v-model="model.docAddress" :max-length="36" placeholder="请输入存放位置" disabled ></a-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="档案所属团队" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="docTeamId">
                  <select-team-input :multi="false" :tdlx="3" :disabled="formDisabled" v-model="model.docTeamId" disabled />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="是否外带" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="isOutside">
                  <j-dict-select-tag :disabled="formDisabled" type="radio" v-model="model.isOutside" dictCode="yes_or_no" placeholder="请选择是否外带" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="借阅日期" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="referenceTime">
                  <j-date :disabled="formDisabled" placeholder="请选择借阅日期" v-model="model.referenceTime" style="width: 100%" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="份数" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="totalNumber">
                  <a-input-number
                    :disabled="formDisabled"
                    :max="999999999"
                    :min="0"
                    :precision="0"
                    v-model="model.totalNumber"
                    placeholder="请输入份数"
                    style="width: 100%" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="预计归还时间" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="backTime">
                  <j-date :disabled="formDisabled" placeholder="请选择预计归还时间" v-model="model.backTime" style="width: 100%" />
                </a-form-model-item>
              </a-col>
              <a-col :span="24">
                <a-form-model-item label="借阅事由" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="referenceReason">
                  <a-textarea :disabled="formDisabled" v-model="model.referenceReason" rows="4" :max-length="500" placeholder="请输入借阅事由" />
                </a-form-model-item>
              </a-col>
            </a-row>
          </a-collapse-panel>

          <a-collapse-panel key="3" header="附件信息">
            <a-row :gutter="48">
              <a-col :span="8">
                <a-form-model-item label="附件" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="attachment">
                  <j-upload :disabled="formDisabled" v-model="model.attachment" ></j-upload>
                </a-form-model-item>
              </a-col>
              <!-- <a-col v-if="showFlowSubmitButton" :span="24" style="text-align: center">
            <a-button @click="submitForm">提 交</a-button>
          </a-col> -->
            </a-row>
          </a-collapse-panel>
        </a-collapse>

      </a-form-model>
    </j-form-container>
    <a-row type="flex" justify="center">
      <a-col :span="24">
        <!-- 流程历史跟踪 -->
        <common-flow-list v-if="formBpm && model.bpmStatus !== '1'" :formData="formData"></common-flow-list>
      </a-col>
      <a-col :span="24" style="text-align: center;margin-top: 15px">
        <a-button type="primary" v-if="formBpm" :style="{ marginRight: showFlowSubmitButton?'10px':'0px' }" @click="onPrint">打印</a-button>
        <a-button @click="submitForm('submit')" v-if="showFlowSubmitButton">提 交</a-button>
      </a-col>
    </a-row>
    <ErpOaDocBaseInfoPenetrate ref="docRef"></ErpOaDocBaseInfoPenetrate>
    <ErpProjectArchivePenetrate ref="projectArchiveRef"></ErpProjectArchivePenetrate>
    <ErpOaDocReferenceBillFormPrint v-if="formBpm" id="printContent" class="print_style" :formData="model" :formDataHistory="formData"></ErpOaDocReferenceBillFormPrint>
  </a-spin>
</template>

<script>

  import { httpAction, getAction } from '@/api/manage'
  import { validateDuplicateValue } from '@/utils/util'
  import SelectUserByDep from '@/views/scy/components/SelectUserByDep'
  import SelectTeamInput from '@/views/scy/components/SelectTeamInput'
  import SelectOaDocBaseInput from '@/views/scy/components/SelectOaDocBaseInput'
  import SelectCompanyInput from '@/views/scy/components/SelectCompanyInput'
  import JDictSelectCategory from '@/components/dict/JDictSelectCategory.vue'
  import SelectProjectArchiveInput from '@/views/scy/components/SelectProjectArchiveInput'
  import ErpOaDocBaseInfoPenetrate from '@/views/scy/penetrate/ErpOaDocBaseInfoPenetrate'
  import ErpProjectArchivePenetrate from '@/views/scy/penetrate/ErpProjectArchivePenetrate'
  import ErpOaDocReferenceBillFormPrint from './ErpOaDocReferenceBillFormPrint.vue'
  import CommonFlowList from '@/views/components/CommonFlowList.vue' // 审批历史流程列表组件

  import moment from 'moment'
  import { mapGetters } from 'vuex'
  import Print from '@/utils/print/printarea.js';

  export default {
    name: 'ErpOaDocReferenceBillForm',
    components: {
      SelectUserByDep,
      SelectTeamInput,
      SelectCompanyInput,
      JDictSelectCategory,
      SelectOaDocBaseInput,
      ErpOaDocBaseInfoPenetrate,
      SelectProjectArchiveInput,
      ErpProjectArchivePenetrate,
      ErpOaDocReferenceBillFormPrint,
      CommonFlowList,
    },
    props: {
      // 流程表单data
      formData: {
        type: Object,
        default: () => {},
        required: false
      },
      // 表单模式：true流程表单 false普通表单
      formBpm: {
        type: Boolean,
        default: false,
        required: false
      },
      // 表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false
      }
    },
    data () {
      return {
        activeKey: ['1', '2', '3'],
        model: {
         },
        labelCol: {
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 24 }
        },
        confirmLoading: false,
        validatorRules: {
        docBigCategory: [
            { required: true, message: '请选择档案大类!', whitespace: true }
        ],
          teamId: [
            { required: true, message: '请选择申请人所属团队!', whitespace: true }
        ],
        docSmallCategory: [
            { required: true, message: '请选择档案小类!', whitespace: true }
        ],
        isOutside: [
            { required: true, message: '请选择是否外带!', whitespace: true }
        ],
        referenceTime: [
            { required: true, message: '请选择借阅日期!', whitespace: true }
        ],
        docName: [
            { required: true, message: '请选择文件名称!' }
        ],
        docTeamId: [
            { required: true, message: '请选择档案所属团队!' }
        ],
        backTime: [
            { required: true, message: '请选择预计归还时间!', whitespace: true }
        ],
        referenceReason: [
            { required: true, message: '请输入借阅事由!', whitespace: true }
        ]
        },
        url: {
          add: '/api/erp/oa/doc/erpOaDocReferenceBill/add',
          edit: '/api/erp/oa/doc/erpOaDocReferenceBill/edit',
          queryById: '/api/erp/oa/doc/erpOaDocReferenceBill/queryById',
          getBillNo: '/api/erp/oa/doc/erpOaDocReferenceBill/getBillNo',
          queryBaseInfoById: '/api/erp/oa/doc/erpOaDocBaseInfo/queryById',
          queryByCode: '/api/erpmng/sys/category/queryByCode',
          queryArchiveFileById: '/api/erp/omc/projectarchive/erpProjectArchiveFile/queryById'
        }
      }
    },
    computed: {
      formDisabled() {
        if (this.formBpm === true) {
          if (this.formData.disabled === false) {
            return false
          }
          return true
        }
        return this.disabled
      },
      showFlowSubmitButton() {
        if (this.formBpm === true) {
          if (this.formData.disabled === false) {
            return true
          }
        }
        return false
      }
    },
    created () {
       // 备份model原始值
      this.modelDefault = JSON.parse(JSON.stringify(this.model));
      // 如果是流程中表单，则需要加载流程表单data
      this.showFlowData();
    },
    methods: {
      selectProjectArchive(data) {
        if (data[0]) {
          this.$set(this.model, 'docTeamId', data[0].archiveBelongingTeam)
          this.$set(this.model, 'docClassification', data[0].secrecyLevel)
          this.$set(this.model, 'docAddress', data[0].archiveLocation)
        }
      },
      selectDoc(data) {
        if (data[0]) {
          this.$set(this.model, 'docTeamId', data[0].teamId)
          this.$set(this.model, 'docClassification', data[0].classification)
          this.$set(this.model, 'docAddress', data[0].docAddress)
        }
      },
      // 获取编号
      getBillNo() {
        let that = this
        getAction(this.url.getBillNo, {}).then((res) => {
          if (res.success) {
            let data = res.result.records || res.result
            this.$set(this.model, 'billNo', data)
          }
        })
      },
      modifyCategory(data) {
        if (data) {
          if (this.model.docSmallCategory) {
            this.$set(this.model, 'docSmallCategory', null);
          }
          this.$set(this.model, 'docName', null);
          this.$set(this.model, 'docTeamId', null)
          this.$set(this.model, 'docClassification', null)
          this.$set(this.model, 'docAddress', null)
        }
      },
      modifySmallCategory(data) {
        if (data) {
          this.$set(this.model, 'docName', null);
          this.$set(this.model, 'docTeamId', null)
          this.$set(this.model, 'docClassification', null)
          this.$set(this.model, 'docAddress', null)
        }
      },
      ...mapGetters(['userInfo']),
      add () {
        this.edit(this.modelDefault);
        this.getBillNo();
        this.model.employeeId = this.userInfo().empId;
        this.model.departId = this.userInfo().deptId;
        this.model.createTime = moment().format('YYYY-MM-DD HH:mm:ss');
      },
      edit (record) {
        this.$refs.form.resetFields();
        this.model = Object.assign({}, record);
        this.visible = true;
        // 加载关联的档案基础信息
        if (this.formDisabled && this.model.docName && (this.model.docBigCategory == 'A04A01' || this.model.docBigCategory == 'A04A02')) {
          getAction(this.url.queryBaseInfoById, { 'id': this.model.docName }).then((res) => {
            if (res.success) {
              let data = res.result
              this.$set(this.model, 'docBillNo', data.billNo);
            }
          })
        } else if (this.formDisabled && this.model.docName && (this.model.docBigCategory != 'A04A01' && this.model.docBigCategory != 'A04A02')) {
          getAction(this.url.queryArchiveFileById, { 'id': this.model.docName }).then((res) => {
            if (res.success) {
              let data = res.result
              this.$set(this.model, 'docBillNo', data.fileNo);
            }
          })
        }
      },
      goDocDetail(model) {
        if (model.docBigCategory == 'A04A01' || model.docBigCategory == 'A04A02') {
          this.$refs.docRef.initData(model.docName);
          this.$refs.docRef.visible = true;
        } else {
          this.$refs.projectArchiveRef.initData(model.docName);
          this.$refs.projectArchiveRef.visible = true;
        }
      },
      // 渲染流程表单数据
      showFlowData() {
        if (this.formBpm === true) {
          let params = { id: this.formData.dataId };
          getAction(this.url.queryById, params).then((res) => {
            if (res.success) {
              this.edit(res.result);
            }
          });
        }
      },
      getCategoryName(code) {
        return new Promise((resolve, rej) => {
 getAction(this.url.queryByCode, { code: code }).then((res) => {
          if (res.success) {
            return resolve(res.result ? res.result.name : '');
          } else {
            return resolve('');
          }
        })
});
      },

      submitForm(type) {
        const that = this;
        if (type == 'draft') {
          // 代表保存草稿不做校验
          this.submit(type)
        } else if (type == 'submit') {
          // 触发表单验证
          this.$refs.form.validate(valid => {
            if (valid) {
              that.submit(type)
            } else {
              that.$emit('unButtonDisable')
            }
          })
        } else {
          console.log('传参数，保存：draft，提交：submit')
        }
      },

      async setBpmBizTitle() {
        let docBigCategory = await this.getCategoryName(this.model.docBigCategory);
        let docSmallCategory = await this.getCategoryName(this.model.docSmallCategory);
        this.$set(this.model, 'bpmBizTitle', '档案查阅单' + '-' + (docBigCategory ? docBigCategory + '-' : '') + (docSmallCategory ? docSmallCategory + '-' : '') + this.userInfo().realname + '-' + moment(this.model.createTime).format('YYYY年MM月DD日'));
				// const docBigCategory = await this.getCategoryName(this.model.docBigCategory)
				// const docSmallCategory = await this.getCategoryName(this.model.docSmallCategory)
				// this.model.bpmBizTitle =
				// 	'档案查阅单' +
				// 	'-' +
				// 	(docBigCategory? docBigCategory +  '-' : '') + (docSmallCategory ? docSmallCategory + '-' : '') +
				// 	this.userInfo?.employee?.name +
				// 	'-' +
				// 	moment(this.model.createTime).format('YYYY年MM月DD日')
			},
      async submit (type) {
        const that = this;
        that.confirmLoading = true;
        let httpurl = '';
        let method = '';
        if (!this.model.id) {
          httpurl += this.url.add;
          method = 'post';
        } else {
          httpurl += this.url.edit;
          method = 'put';
        }
        await this.setBpmBizTitle()
        // let docBigCategory = await this.getCategoryName(this.model.docBigCategory);
        // let docSmallCategory = await this.getCategoryName(this.model.docSmallCategory);
        // this.$set(this.model, 'bpmBizTitle', '档案查阅单' + '-' + (docBigCategory ? docBigCategory + '-' : '') + (docSmallCategory ? docSmallCategory + '-' : '') + this.userInfo().realname + '-' + moment(this.model.createTime).format('YYYY年MM月DD日'));
        httpAction(httpurl, this.model, method).then((res) => {
          if (res.success) {
            that.$message.success(res.message);
            if (method == 'post') {
              that.model.id = res.result;
            }
            that.$emit('ok', type, that.model);
          } else {
            that.$message.warning(res.message);
            that.$emit('unButtonDisable');
          }
        }).catch((error) => {
          that.$emit('unButtonDisable', error);
        }).finally(() => {
          that.confirmLoading = false;
        })
      },
      // 点击打印
      onPrint () {
        let print = new Print({
          el: '#printContent',
          popTitle: '档案查阅单详情 · 禾美环保',
          endCallback() {

          }
        })
      }
    }
  }
</script>
